package org.huawei260.TiKu.C.C048;

import java.time.LocalTime;
import java.util.PriorityQueue;
import java.util.Scanner;

/**
 * @Auther: qingle
 * @Date: 2024/10/22-16:22
 * @Description:
 * @version: 1.0
 */
public class C048_AppRegistration {

	static class AppRegistration implements Comparable<AppRegistration> {
		String appName;
		int priority;
		LocalTime startTime;
		LocalTime endTime;

		public AppRegistration(String appName, int priority, LocalTime startTime, LocalTime endTime) {
			this.appName = appName;
			this.priority = priority;
			this.startTime = startTime;
			this.endTime = endTime;
		}

		@Override
		public int compareTo(AppRegistration o) {
			if (this.priority != o.priority) {
				return o.priority - this.priority; // Higher priority comes first
			}
			// If priorities are the same, compare start times to ensure later apps override earlier ones
			return this.startTime.compareTo(o.startTime);
		}
	}

	public static class AppScheduler {
		private final PriorityQueue<AppRegistration> appQueue = new PriorityQueue<>();

		public void registerApp(String appName, int priority, String startTime, String endTime) {
			LocalTime start = LocalTime.parse(startTime);
			LocalTime end = LocalTime.parse(endTime);
			// Check for overlapping times and remove lower priority apps
			PriorityQueue<AppRegistration> tempQueue = new PriorityQueue<>(appQueue);
			tempQueue.add(new AppRegistration(appName, priority, start, end));
			while (!tempQueue.isEmpty()) {
				AppRegistration app = tempQueue.poll();
				if (!appQueue.isEmpty() && appQueue.peek().startTime.equals(app.startTime)) {
					continue;
				}
				appQueue.add(app);
			}
		}

		public String getAppAtTime(String time) {
			LocalTime queryTime = LocalTime.parse(time);
			for (AppRegistration app : appQueue) {
				if (queryTime.isAfter(app.startTime) && queryTime.isBefore(app.endTime)) {
					return app.appName;
				}
			}
			return "NA";
		}

		public static void main(String[] args) {
			Scanner scanner = new Scanner(System.in);
			int N = scanner.nextInt();
			scanner.nextLine(); // Consume the newline character

			AppScheduler scheduler = new AppScheduler();

			for (int i = 0; i < N; i++) {
				String appName = scanner.next();
				int priority = scanner.nextInt();
				scanner.nextLine(); // Consume the space character
				String startTime = scanner.next();
				String endTime = scanner.next();
				scheduler.registerApp(appName, priority, startTime, endTime);
			}

			String queryTime = scanner.next();
			System.out.println(scheduler.getAppAtTime(queryTime));
		}
	}
}
